#!/usr/bin/env python
# encoding: utf-8
"""
@Author: Beam
@Mail:506556658@qq.com
@file: login.py.py
@time: 2017/8/10 10:24
"""

from django.shortcuts import render,HttpResponse,redirect
from cmdb.models import User
from cmdb.models import BookInfo
from cmdb.models import BookGroup
from cmdb import models



#登录页
def login(request):
    if request.method == 'GET':
        return render(request,'login.html')
    elif request.method == 'POST':
        u = request.POST.get('username')
        p = request.POST.get('password')
        obj = models.User.objects.filter(username = u,password = p).first()

        if obj:
            return redirect('/cmdb/home')
        else:
            err_msg = '该用户不存在'
            return render(request, 'login.html', {'err_msg': err_msg})
    else:
        return HttpResponse('404')

#查看全部书本以及添加书本
def home(request):
    if request.method == 'POST':
        bookname = request.POST.get('bookname')
        author = request.POST.get('author')
        price = request.POST.get('price')
        date = request.POST.get('date')
        btype = request.POST.get('booktype')
        bookinfo = BookInfo()
        bookinfo.bookname = bookname
        bookinfo.author = author
        bookinfo.price = price
        bookinfo.date = date
        bookinfo.booktype_id = btype
        bookinfo.save()
    booklist = BookInfo.objects.all()
    booktypelist = BookGroup.objects.all()
    return render(request,'projects.html',{'booklists':booklist,'booktypelist':booktypelist})

#书本详细页
def bkdetail(request,nid):
    obj = models.BookInfo.objects.filter(id = nid).first()
    return render(request,'bookdetail.html',{'bkdetail':obj})

#删除书本
def bkdelete(request,nid):
    models.BookInfo.objects.filter(id=nid).delete()
    return redirect('/cmdb/home')

#编辑书本
def bkedit(request,nid):
    if request.method == 'GET':
        obj = models.BookInfo.objects.filter(id=nid).first()
        booktypelist = BookGroup.objects.all()
        print(obj)
        return render(request,'bookedit.html', {'bkinfo': obj,'BKList':booktypelist})
    elif request.method == 'POST':
        b = request.POST.get('bookname')
        a = request.POST.get('author')
        p = request.POST.get('price')
        d = request.POST.get('date')
        btype = request.POST.get('booktype')
        obj = models.BookInfo.objects.filter(id = nid).update(bookname=b,author=a,price=p,date=d,booktype_id=btype)
        return redirect('/cmdb/home')
